package com.flyco.modules.pms.controller;

import java.util.*;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.flyco.common.api.vo.Result;
import com.flyco.common.system.query.QueryGenerator;
import com.flyco.common.aspect.annotation.AutoLog;
import com.flyco.common.system.vo.LoginUser;
import com.flyco.common.util.oConvertUtils;
import com.flyco.modules.pms.entity.PmsBrand;
import com.flyco.modules.pms.entity.PmsProductCategory;
import com.flyco.modules.pms.service.IPmsProductCategoryService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.flyco.modules.system.entity.SysPartner;
import com.flyco.modules.system.service.ISysPartnerService;
import lombok.extern.slf4j.Slf4j;
import com.flyco.common.system.base.controller.BaseController;
import com.flyco.poi.excel.ExcelImportUtil;
import com.flyco.poi.excel.def.NormalExcelConstants;
import com.flyco.poi.excel.entity.ExportParams;
import com.flyco.poi.excel.entity.ImportParams;
import com.flyco.poi.excel.view.EntityExcelView;

import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

 /**
 * @Description: 商品分类
 * @Author: flyco
 * @Date:   2019-11-15
 * @Version: V1.0
 */
@Slf4j
@Api(tags="商品分类")
@RestController
@RequestMapping("/f/pms/pmsProductCategory")
public class PmsProductCategoryController extends BaseController<PmsProductCategory, IPmsProductCategoryService> {
	@Autowired
	private IPmsProductCategoryService pmsProductCategoryService;
	 @Autowired
	 private ISysPartnerService sysPartnerService;
	
	/**
	 * 分页列表查询
	 *
	 * @param pmsProductCategory
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "商品分类-分页列表查询")
	@ApiOperation(value="商品分类-分页列表查询", notes="商品分类-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(PmsProductCategory pmsProductCategory,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<PmsProductCategory> queryWrapper = QueryGenerator.initQueryWrapper(pmsProductCategory, req.getParameterMap());
		Page<PmsProductCategory> page = new Page<PmsProductCategory>(pageNo, pageSize);
		IPage<PmsProductCategory> pageList = pmsProductCategoryService.page(page, queryWrapper);
		pageList.getRecords().forEach(a->{
			if(a.getParentId()!=null){
				PmsProductCategory productCategory=pmsProductCategoryService.getById(a.getParentId());
				a.setParentName(productCategory!=null?productCategory.getName():"");
			}
		});
		return Result.ok(pageList);
	}

	 @AutoLog(value = "商品分类-查询一级分类")
	 @ApiOperation(value="商品分类-查询一级分类", notes="商品分类-查询一级分类")
	 @GetMapping(value = "/queryLevelList")
	 public Result<?> queryLevelList(@RequestParam(name = "id") Long id) {
		 Result<List<PmsProductCategory>> result = new Result<>();
		 LambdaQueryWrapper<PmsProductCategory> query = new LambdaQueryWrapper<>();
		 query.eq(PmsProductCategory::getLevel,1);
		 query.orderByAsc(PmsProductCategory::getSort);
		 PmsProductCategory firstCategory = new PmsProductCategory();
		 firstCategory.setId(0l);
		 firstCategory.setName("无上级分类");
		 List<PmsProductCategory> list = pmsProductCategoryService.list(query);
		 list.add(0,firstCategory);
		 //因为暂时支支持两级分类，所以这里不用递归，走单次循环即可
         list.forEach(a->{
             List<PmsProductCategory> children = pmsProductCategoryService.list(new LambdaQueryWrapper<PmsProductCategory>().eq(PmsProductCategory::getParentId,a.getId()));
            if(children!=null){
                a.setChildren(children);
            }
         });
		 result.setResult(list);
		 result.setSuccess(true);
		 return result;
	 }
     @AutoLog(value = "商品分类-查询一级分类及对应的二级分类")
     @ApiOperation(value="商品分类-查询一级分类及对应的二级分类", notes="商品分类-查询一级分类及对应的二级分类")
     @GetMapping(value = "/queryLevelListAndChild")
     public Result<?> queryLevelListAndChild() {
         Result<List<PmsProductCategory>> result = new Result<>();
         LambdaQueryWrapper<PmsProductCategory> query = new LambdaQueryWrapper<>();
         query.eq(PmsProductCategory::getLevel,1);
         query.orderByAsc(PmsProductCategory::getSort);
         List<PmsProductCategory> list = pmsProductCategoryService.list(query);
         //因为暂时支支持两级分类，所以这里不用递归，走单次循环即可
         list.forEach(a->{
             List<PmsProductCategory> children = pmsProductCategoryService.list(new LambdaQueryWrapper<PmsProductCategory>().eq(PmsProductCategory::getParentId,a.getId()));
             if(children!=null){
                 a.setChildren(children);
             }
         });
         result.setResult(list);
         result.setSuccess(true);
         return result;
     }

	 /**
	  * 获取分类列表
	  *
	  * @return
	  */
	 @AutoLog(value = "商品分类-获取分类列表")
	 @ApiOperation(value = "商品分类-获取分类列表", notes = "商品分类-获取分类列表")
	 @GetMapping(value = "/getProductCategorys")
	 public Result<?> getProductCategorys() {
		 LambdaQueryWrapper<PmsProductCategory> query = new LambdaQueryWrapper<>();
//		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
//		 SysPartner partner = sysPartnerService.getById(sysUser.getPartnerId());
//		 query.eq(PmsProductCategory::getBrandId, partner.getBrandId());
		 query.eq(PmsProductCategory::getShowStatus, "1");
		 query.orderByAsc(PmsProductCategory::getSort);
		 List<PmsProductCategory> categorys = pmsProductCategoryService.list(query);
		 return Result.ok(categorys);
	 }
	
	/**
	 * 添加
	 *
	 * @param pmsProductCategory
	 * @return
	 */
	@AutoLog(value = "商品分类-添加")
	@ApiOperation(value="商品分类-添加", notes="商品分类-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody PmsProductCategory pmsProductCategory) {
		setCategoryLevel(pmsProductCategory);
		pmsProductCategoryService.save(pmsProductCategory);
		return Result.ok("添加成功！");
	}

	 /**
	  * 根据分类的parentId设置分类的level
	  */
	 private void setCategoryLevel(PmsProductCategory productCategory) {
		 //没有父分类时为一级分类
		 if (productCategory.getParentId() == 0) {
			 productCategory.setLevel(1);
		 } else {
			 //有父分类时选择根据父分类level设置
			 PmsProductCategory parentCategory = pmsProductCategoryService.getById(productCategory.getParentId());
			 if (parentCategory != null) {
				 productCategory.setLevel(parentCategory.getLevel() + 1);
			 } else {
				 productCategory.setLevel(1);
			 }
		 }
	 }
	
	/**
	 * 编辑
	 *
	 * @param pmsProductCategory
	 * @return
	 */
	@AutoLog(value = "商品分类-编辑")
	@ApiOperation(value="商品分类-编辑", notes="商品分类-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody PmsProductCategory pmsProductCategory) {
		setCategoryLevel(pmsProductCategory);
		boolean ok = pmsProductCategoryService.updateById(pmsProductCategory);
		if(ok)
			return Result.ok("编辑成功!");
		else
			return Result.error("编辑失败");
	}
	
	/**
	 * 通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "商品分类-通过id删除")
	@ApiOperation(value="商品分类-通过id删除", notes="商品分类-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		pmsProductCategoryService.removeById(id);
		return Result.ok("删除成功!");
	}
	
	/**
	 * 批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "商品分类-批量删除")
	@ApiOperation(value="商品分类-批量删除", notes="商品分类-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.pmsProductCategoryService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.ok("批量删除成功！");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "商品分类-通过id查询")
	@ApiOperation(value="商品分类-通过id查询", notes="商品分类-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		PmsProductCategory pmsProductCategory = pmsProductCategoryService.getById(id);
		return Result.ok(pmsProductCategory);
	}

  /**
   * 导出excel
   *
   * @param request
   * @param pmsProductCategory
   */
  @RequestMapping(value = "/exportXls")
  public ModelAndView exportXls(HttpServletRequest request, PmsProductCategory pmsProductCategory) {
      return super.exportXls(request, pmsProductCategory, PmsProductCategory.class, "商品分类");
  }

  /**
   * 通过excel导入数据
   *
   * @param request
   * @param response
   * @return
   */
  @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
  public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      return super.importExcel(request, response, PmsProductCategory.class);
  }

}
